package com.yuanda.wordhot.repository;

import java.util.List;

import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import com.yuanda.wordhot.entity.UserEntity;

/**
 * 用户持久层
 * @author YuBai
 * @Description
 * @Date 2013-5-1
 * @version 1.0
 * @since 1.0
 */
@Repository
public class UserRepository extends HibernateGenericDAO<UserEntity> implements IRepository<UserEntity>{
	
	/**
	 * 根据Email查找用户
	 * @param email
	 * @return
	 */
	public UserEntity findUserByEmail(String email) {
		Assert.hasText(email);
		return (UserEntity) sessionFactory.getCurrentSession()
				.createCriteria(this.persistClass)
				.add(Restrictions.eq("email", email)).uniqueResult();
	}
	
	/**
	 * 查询用户是否可以注册
	 */
	public boolean isEmailAvailable(String email) {
		return (Integer)sessionFactory.getCurrentSession().createCriteria(this.persistClass)
				.setProjection(Projections.rowCount())
				.add(Restrictions.eq("email", email)).uniqueResult() == 0;
	}
	
	@SuppressWarnings("unchecked")
	public List<UserEntity> getAllUsers(int start, int count) {
		return sessionFactory.getCurrentSession().createCriteria(this.persistClass)
				.addOrder(Order.asc("userId"))
				.setFirstResult(start)
				.setMaxResults(count)
				.setComment("userDAO.getAllUsers")
				.list();
	}
	
	/**
	 * 获取用户总数
	 */
	public long getTotalUsers() {
		return (Long)sessionFactory.getCurrentSession().createCriteria(this.persistClass)
				.setProjection(Projections.rowCount())
				.setCacheable(true)
				.setCacheRegion("userDAO.getTotalUsers")
				.setComment("userDAO.getTotalUsers")
				.uniqueResult();
	}
}
